const $ = require("jquery")
const sql = require("sqlite3").verbose()
const IPC = require("electron").ipcRenderer
var classmate =[]
function getData(){
    const table = $("<table></table>");
    const header = $("<tr></tr>");
    header.append($("<th></th>").text("姓名"));
    table.append(header);

    const database = new sql.Database("Student_DB.db",(err) => {

    })

    database.all('SELECT * FROM student', [], (err, rows) => {
        if (err){
            console.log(err)
        }
        rows.forEach((item) => {
            const row = $("<tr></tr>");
            row.append($("<td></td>").text(item["name"]));
            table.append(row);
        });
    })



    $("#tableContainer").html(table);
    database.close()
}

let sqlText=""

const select = $("#select")
const inp = $("#inp")
$(document).ready(function (){
    getData()
})

let model="1"
select.change(function (){
    model=select.val()
})



$("#sub").click(function (){
    switch (model){
        case "1":
            sqlText='insert into student(name) values (?)'
            DB()
            break;
        case "2":
            sqlText='delete from student where name = ?'
            DB()
            break;
        case "3":
            sqlText=''
            FromArray()
            break;
        case "4":
            if (inp.val()==="yes"){
                sqlText=''
                deleteAll()
            }
            break;
    }

})

function FromArray(){
    const database = new sql.Database("./Student_DB.db", (err) => {
        if (err) {
            console.log(err);
        }
    });
    dat = inp.val()
    dat = dat.replace(/[“”‘’"'\s\n]/g,"")
    dat = dat.split(",")

    let insertPromises = dat.map((name) => {
        return new Promise((resolve, reject) => {
            database.run('insert into student(name) values(?)', name, (err) => {
                if (err) {
                    IPC.send("ERR", err);
                    reject(err);
                } else {
                    resolve();
                }
            });
        });
    });
    IPC.send("reload")
    Promise.all(insertPromises)
        .then(() => {
            location.reload();
        })
        .catch((error) => {
            console.error("插入失败:", error);
        });

}

function DB(){
    const database = new sql.Database("./Student_DB.db",(err) => {
        console.log(err)
    })
    database.run(sqlText,inp.val(),(err)=>{
        if (err){
            IPC.send("ERR",err)
        }
        IPC.send("reload")
        location.reload()
    })
}
function deleteAll(){
    const database = new sql.Database("./Student_DB.db",(err) => {
        console.log(err)
    })
    database.run('delete from student',[],(err)=>{
        if (err){
            IPC.send("ERR",err)
        }
        IPC.send("reload")
        location.reload()
    })

}
